/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {useContext, useCallback, useState, useEffect} from 'react';
import type {ReactNode} from 'react';
import {View, Image, StyleSheet, TouchableOpacity} from 'react-native';
import type {ViewStyle} from 'react-native';
import {useBreakpointValue, useHeightBreakpointValue} from '@hadss/react_native_adaptive_layout';
import Video from 'react-native-video';
import Context from '../../Context';
import {emitter} from '../../EventEmitter';
import type {ActionType} from '../../EventEmitter/types';
import {Fold} from '@hadss/react_native_adaptive_layout';
import RNThumbnail from 'react-native-thumbnail';
import React from 'react';

const PHOTO_ACTION = require('../../../../../assets/pic/take_photo.png');
const VIDEO_START = require('../../../../../assets/pic/start_record.png');
const VIDEO_STOP = require('../../../../../assets/pic/stop_record.png');
const ZOOM = require('../../../../../assets/pic/zoom_1.png');
const SWITCH = require('../../../../../assets/pic/switch_camera.png');

/**
 * @description 相机操作按钮三金刚
 * @returns ReactNode
 */
const Action = () : JSX.Element => {
  const {mode, isRecording, path, setIsRecording, mediaType} = useContext(Context);
  /**
   * @description 相机底部action操作按钮，根据不同屏幕类型断点自行设置样式，合理使用布局方式！
   */
  const containerStyle = useBreakpointValue<ViewStyle>({
    base: {
      columnGap: 46,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });
  const [thumbnail, setThumbnail] = React.useState(null);

  const onPress = (data?: ActionType): void => {
    if (data) {
      emitter.publish<ActionType>('camera:action', data);
    } else {
      let command: ActionType;
      if (mode === 'photo') {
        command = 'take_photo';
      } else {
        if (isRecording) {
          command = 'stop_record';
          setIsRecording(false);
        } else {
          command = 'start_record';
          setIsRecording(true);
        }
      }
      emitter.publish<ActionType>('camera:action', command);
    }
  };
  const isSmall = useHeightBreakpointValue<boolean>({
    base: false,
    sm: true,
    md: true,
    lg: false,
  });
  const renderIcon = useBreakpointValue<ReactNode>({
    base: (
      <TouchableOpacity
        onPress={() : void => {
          onPress('switch');
        }}>
        <Image source={SWITCH} style={styles.switch} />
      </TouchableOpacity>
    ),
    sm: (
      <TouchableOpacity
        onPress={() : void => {
          !isSmall || (isSmall && Fold.getFoldStatus() !== 'folded') ? onPress('switch') : null;
        }}>
        <Image source={isSmall && Fold.getFoldStatus() === 'folded' ? ZOOM : SWITCH} style={styles.switch} />
      </TouchableOpacity>
    ),
  });
  /**
   * @description 生成视频缩略图（异步函数，单独提取避免渲染阻塞）
   * @param videoPath 视频本地路径
   */
  const generateThumbnail = useCallback(async (videoPath: string) : Promise<void> => {
    if (!videoPath) {
      return; 
  }

    try {
      const result = await RNThumbnail.get(videoPath);
      setThumbnail(result.path); 

    } catch (error) {
      setThumbnail(null);
    } 
  }, []);

  /**
   * @description 监听path变化，自动生成缩略图（视频模式下）
   */
  useEffect(() : void => {
    if (mediaType === 'video' && typeof path.uri === 'string') {
      generateThumbnail(path.uri);
    }
  }, [path, generateThumbnail]);

  /**
   * @description 渲染预览区域（照片直接显示，视频显示缩略图）
   */
  const renderPreview = (): JSX.Element => {

    return <Image source={{ uri: thumbnail }} style={styles.switch} resizeMode="cover" />;
  };

  return (
    <View style={containerStyle}>
      {!isRecording && (
        <TouchableOpacity
          style={[styles.switch, {borderRadius: 44}]}
          onPress={() : void => {
            onPress('preview');
          }}>
          {mediaType === 'photo' ? <Image source={path} style={styles.switch} /> : <>{renderPreview()}</>}
        </TouchableOpacity>
      )}
      <TouchableOpacity onPress={(): void => onPress()}>
        {mode === 'photo' ? (
          <Image source={PHOTO_ACTION} style={styles.capture} />
        ) : isRecording ? (
          <Image source={VIDEO_STOP} style={styles.capture} />
        ) : (
          <Image source={VIDEO_START} style={styles.capture} />
        )}
      </TouchableOpacity>
      {!isRecording && renderIcon}
    </View>
  );
};

const styles = StyleSheet.create({
  capture: {
    width: 76,
    height: 76,
  },
  switch: {
    width: 44,
    height: 44,
    overflow: 'hidden',
  },
});

export default Action;
